﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShengYueWorkShop.BLL.PublicHelper
{
    /// <summary>
    /// 图片帮助类
    /// </summary>
    public class PicHelper
    {
        /// <summary>
        /// 将图片转换成字节
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static byte[] ResizeAndConvertToBytes(string imagePath)
        {
            FileInfo fFileInfo = new FileInfo(imagePath);
            double fFileSizeMb = fFileInfo.Length / 1024 / 1024;
            Image fImage = Image.FromFile(imagePath);
            Bitmap resizedImage;
            ///如果图片大于规定值
            if (fFileSizeMb > Tcp.TcpOperationCommand.PicMaxMb)
            {
                //按比例缩小图片
                int fNewWidth = Convert.ToInt16((double)fImage.Width * Tcp.TcpOperationCommand.PicPercent);
                int fNewHitght = Convert.ToInt16((double)fImage.Height * Tcp.TcpOperationCommand.PicPercent);
                resizedImage = new Bitmap(fNewWidth, fNewHitght);
                //缩小图片
                using (Graphics g = Graphics.FromImage(resizedImage))
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(fImage, 0, 0, fNewWidth, fNewHitght);
                }
            }
            else
            {
                resizedImage =new Bitmap(fImage);
            }
            //将图片转换为数据流
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // 将缩小后的图片保存到内存流中
                resizedImage.Save(memoryStream, ImageFormat.Jpeg);
                // 将内存流转换为字节数组
                byte[] imageBytes = memoryStream.ToArray();
                return imageBytes;
            }
        }
        /// <summary>
        /// 将字节转换成图片
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static Image BytesToImage(byte[] bytes)
        {
            using (var ms = new MemoryStream(bytes))
            {
                return Image.FromStream(ms);
            }
        }
    }
}
